package org.lingshi.shopping_file_service.service;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.dubbo.config.annotation.DubboService;
import org.lingshi.common.service.IFileService;
import org.springframework.beans.factory.annotation.Value;

import java.io.ByteArrayInputStream;
import java.util.List;

@DubboService
public class FileServiceImpl implements IFileService {
    @Value("${upload.endpoint}")
    private String endpoint;
    @Value("${upload.bucket}")
    private String bucketName;
    @Value("${upload.accessKey}")
    private String accessKey;
    @Value("${upload.secretKey}")
    private String secretKey;
    @Value("${upload.serverUrl}")
    private String serverUrl;

    public OSS initOss(){
        OSS oss = new OSSClientBuilder().build(endpoint, accessKey, secretKey);
        return oss;
    }

    /**
     * 上传文件
     *
     * @param fileBytes 图片文件转成的字节数组
     * @param fileName  文件名
     * @return 上传后的文件访问路径
     */
    @Override
    public String uploadImage(byte[] fileBytes, String fileName) {
        OSS oss = initOss();
        try {
            String extName = FileNameUtil.extName(fileName);
            String newFileName = RandomUtil.randomString(20);
            newFileName = newFileName + StrUtil.DOT+extName;
            System.out.println("newFileName = "+newFileName);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
            oss.putObject(bucketName,newFileName,inputStream);
            return serverUrl+StrUtil.SLASH+newFileName;
        }finally {
            //关闭oss客户端
            oss.shutdown();
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件路径
     */
    @Override
    public void delete(String filePath) {
        OSS oss = initOss();
        try {
            List<String> list = StrUtil.split(filePath, "/");
            String filename = list.get(list.size() - 1);
            oss.deleteObject(bucketName,filename);
        }finally {
            oss.shutdown();
        }
    }
}
